#include "PermissionManager.h"
#include <QFile>
#include <QDir>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDebug>

namespace CollaborativeDesign {

PermissionManager::PermissionManager()
    : QObject(nullptr),
      m_configFilePath("permissions.json")
{
}

PermissionManager::~PermissionManager()
{
    // 保存权限配置
    savePermissionConfig();
}

bool PermissionManager::initialize()
{
    // 加载权限配置
    return loadPermissionConfig();
}

bool PermissionManager::hasPermission(const QString& userId, const QString& resourceId, PermissionType permission)
{
    // 检查用户-资源-权限映射
    if (m_userResourcePermissions.contains(userId) && 
        m_userResourcePermissions[userId].contains(resourceId)) {
        
        // 检查是否有指定权限
        return m_userResourcePermissions[userId][resourceId].contains(permission);
    }
    
    // 检查用户-资源-角色映射
    if (m_userResourceRoles.contains(userId) && 
        m_userResourceRoles[userId].contains(resourceId)) {
        
        // 获取角色权限
        RoleType role = m_userResourceRoles[userId][resourceId];
        QSet<PermissionType> rolePermissions = getRolePermissions(role);
        
        // 检查角色是否有指定权限
        return rolePermissions.contains(permission);
    }
    
    return false;
}

bool PermissionManager::grantPermission(const QString& userId, const QString& resourceId, PermissionType permission)
{
    // 验证操作权限
    if (!validateOperation(userId, resourceId, PermissionType::Admin)) {
        qWarning() << "没有授予权限的权限";
        return false;
    }
    
    // 确保用户-资源映射存在
    if (!m_userResourcePermissions.contains(userId)) {
        m_userResourcePermissions[userId] = QMap<QString, QSet<PermissionType>>();
    }
    
    if (!m_userResourcePermissions[userId].contains(resourceId)) {
        m_userResourcePermissions[userId][resourceId] = QSet<PermissionType>();
    }
    
    // 添加权限
    m_userResourcePermissions[userId][resourceId].insert(permission);
    
    // 发送权限变更信号
    emit permissionChanged(userId, resourceId, permission, true);
    
    // 保存权限配置
    savePermissionConfig();
    
    qDebug() << "授予权限:" << userId << resourceId << static_cast<int>(permission);
    return true;
}

bool PermissionManager::revokePermission(const QString& userId, const QString& resourceId, PermissionType permission)
{
    // 验证操作权限
    if (!validateOperation(userId, resourceId, PermissionType::Admin)) {
        qWarning() << "没有撤销权限的权限";
        return false;
    }
    
    // 检查用户-资源-权限映射
    if (m_userResourcePermissions.contains(userId) && 
        m_userResourcePermissions[userId].contains(resourceId)) {
        
        // 移除权限
        m_userResourcePermissions[userId][resourceId].remove(permission);
        
        // 发送权限变更信号
        emit permissionChanged(userId, resourceId, permission, false);
        
        // 保存权限配置
        savePermissionConfig();
        
        qDebug() << "撤销权限:" << userId << resourceId << static_cast<int>(permission);
        return true;
    }
    
    return false;
}

bool PermissionManager::setUserRole(const QString& userId, const QString& resourceId, RoleType role)
{
    // 验证操作权限
    if (!validateOperation(userId, resourceId, PermissionType::Admin)) {
        qWarning() << "没有设置角色的权限";
        return false;
    }
    
    // 确保用户-资源-角色映射存在
    if (!m_userResourceRoles.contains(userId)) {
        m_userResourceRoles[userId] = QMap<QString, RoleType>();
    }
    
    // 设置角色
    m_userResourceRoles[userId][resourceId] = role;
    
    // 发送角色变更信号
    emit roleChanged(userId, resourceId, role);
    
    // 保存权限配置
    savePermissionConfig();
    
    qDebug() << "设置角色:" << userId << resourceId << static_cast<int>(role);
    return true;
}

RoleType PermissionManager::getUserRole(const QString& userId, const QString& resourceId)
{
    // 检查用户-资源-角色映射
    if (m_userResourceRoles.contains(userId) && 
        m_userResourceRoles[userId].contains(resourceId)) {
        
        return m_userResourceRoles[userId][resourceId];
    }
    
    // 默认为访客角色
    return RoleType::Guest;
}

QMap<QString, QSet<PermissionType>> PermissionManager::getResourcePermissions(const QString& resourceId)
{
    QMap<QString, QSet<PermissionType>> result;
    
    // 遍历所有用户
    for (auto it = m_userResourcePermissions.begin(); it != m_userResourcePermissions.end(); ++it) {
        QString userId = it.key();
        
        // 检查用户是否有该资源的权限
        if (it.value().contains(resourceId)) {
            result[userId] = it.value()[resourceId];
        }
    }
    
    // 遍历所有用户角色
    for (auto it = m_userResourceRoles.begin(); it != m_userResourceRoles.end(); ++it) {
        QString userId = it.key();
        
        // 检查用户是否有该资源的角色
        if (it.value().contains(resourceId)) {
            RoleType role = it.value()[resourceId];
            QSet<PermissionType> rolePermissions = getRolePermissions(role);
            
            // 合并角色权限
            if (result.contains(userId)) {
                result[userId].unite(rolePermissions);
            } else {
                result[userId] = rolePermissions;
            }
        }
    }
    
    return result;
}

QMap<QString, QSet<PermissionType>> PermissionManager::getUserPermissions(const QString& userId)
{
    QMap<QString, QSet<PermissionType>> result;
    
    // 检查用户是否有权限
    if (m_userResourcePermissions.contains(userId)) {
        result = m_userResourcePermissions[userId];
    }
    
    // 检查用户是否有角色
    if (m_userResourceRoles.contains(userId)) {
        // 遍历用户的所有角色
        for (auto it = m_userResourceRoles[userId].begin(); it != m_userResourceRoles[userId].end(); ++it) {
            QString resourceId = it.key();
            RoleType role = it.value();
            QSet<PermissionType> rolePermissions = getRolePermissions(role);
            
            // 合并角色权限
            if (result.contains(resourceId)) {
                result[resourceId].unite(rolePermissions);
            } else {
                result[resourceId] = rolePermissions;
            }
        }
    }
    
    return result;
}

bool PermissionManager::createResourcePermission(const QString& resourceId, const QString& ownerId)
{
    // 设置资源所有者
    m_resourceOwners[resourceId] = ownerId;
    
    // 设置所有者角色
    setUserRole(ownerId, resourceId, RoleType::Owner);
    
    // 保存权限配置
    savePermissionConfig();
    
    qDebug() << "创建资源权限:" << resourceId << ownerId;
    return true;
}

bool PermissionManager::deleteResourcePermission(const QString& resourceId)
{
    // 验证操作权限
    if (!validateOperation("", resourceId, PermissionType::Admin)) {
        qWarning() << "没有删除资源权限的权限";
        return false;
    }
    
    // 移除资源所有者
    m_resourceOwners.remove(resourceId);
    
    // 移除所有用户对该资源的权限
    for (auto it = m_userResourcePermissions.begin(); it != m_userResourcePermissions.end(); ++it) {
        it.value().remove(resourceId);
    }
    
    // 移除所有用户对该资源的角色
    for (auto it = m_userResourceRoles.begin(); it != m_userResourceRoles.end(); ++it) {
        it.value().remove(resourceId);
    }
    
    // 保存权限配置
    savePermissionConfig();
    
    qDebug() << "删除资源权限:" << resourceId;
    return true;
}

QSet<PermissionType> PermissionManager::getRolePermissions(RoleType role)
{
    QSet<PermissionType> permissions;
    
    switch (role) {
        case RoleType::Guest:
            // 访客只有读取权限
            permissions.insert(PermissionType::Read);
            break;
            
        case RoleType::Viewer:
            // 查看者有读取权限
            permissions.insert(PermissionType::Read);
            break;
            
        case RoleType::Editor:
            // 编辑者有读取和写入权限
            permissions.insert(PermissionType::Read);
            permissions.insert(PermissionType::Write);
            break;
            
        case RoleType::Manager:
            // 管理者有读取、写入和删除权限
            permissions.insert(PermissionType::Read);
            permissions.insert(PermissionType::Write);
            permissions.insert(PermissionType::Delete);
            break;
            
        case RoleType::Owner:
            // 所有者有所有权限
            permissions.insert(PermissionType::Read);
            permissions.insert(PermissionType::Write);
            permissions.insert(PermissionType::Delete);
            permissions.insert(PermissionType::Admin);
            break;
    }
    
    return permissions;
}

bool PermissionManager::loadPermissionConfig()
{
    QFile file(m_configFilePath);
    if (!file.exists()) {
        // 配置文件不存在，初始化空配置
        m_userResourcePermissions.clear();
        m_userResourceRoles.clear();
        m_resourceOwners.clear();
        return true;
    }
    
    if (!file.open(QIODevice::ReadOnly)) {
        qWarning() << "无法打开权限配置文件:" << m_configFilePath;
        return false;
    }
    
    QByteArray data = file.readAll();
    file.close();
    
    QJsonDocument doc = QJsonDocument::fromJson(data);
    if (doc.isNull() || !doc.isObject()) {
        qWarning() << "权限配置文件格式错误";
        return false;
    }
    
    QJsonObject rootObj = doc.object();
    
    // 读取用户-资源-权限映射
    m_userResourcePermissions.clear();
    QJsonObject permissionsObj = rootObj["permissions"].toObject();
    
    for (auto userIt = permissionsObj.begin(); userIt != permissionsObj.end(); ++userIt) {
        QString userId = userIt.key();
        QJsonObject resourcesObj = userIt.value().toObject();
        
        for (auto resourceIt = resourcesObj.begin(); resourceIt != resourcesObj.end(); ++resourceIt) {
            QString resourceId = resourceIt.key();
            QJsonArray permissionsArray = resourceIt.value().toArray();
            
            QSet<PermissionType> permissions;
            for (const QJsonValue& value : permissionsArray) {
                permissions.insert(static_cast<PermissionType>(value.toInt()));
            }
            
            m_userResourcePermissions[userId][resourceId] = permissions;
        }
    }
    
    // 读取用户-资源-角色映射
    m_userResourceRoles.clear();
    QJsonObject rolesObj = rootObj["roles"].toObject();
    
    for (auto userIt = rolesObj.begin(); userIt != rolesObj.end(); ++userIt) {
        QString userId = userIt.key();
        QJsonObject resourcesObj = userIt.value().toObject();
        
        for (auto resourceIt = resourcesObj.begin(); resourceIt != resourcesObj.end(); ++resourceIt) {
            QString resourceId = resourceIt.key();
            int roleValue = resourceIt.value().toInt();
            
            m_userResourceRoles[userId][resourceId] = static_cast<RoleType>(roleValue);
        }
    }
    
    // 读取资源-所有者映射
    m_resourceOwners.clear();
    QJsonObject ownersObj = rootObj["owners"].toObject();
    
    for (auto it = ownersObj.begin(); it != ownersObj.end(); ++it) {
        QString resourceId = it.key();
        QString ownerId = it.value().toString();
        
        m_resourceOwners[resourceId] = ownerId;
    }
    
    return true;
}

bool PermissionManager::savePermissionConfig()
{
    // 创建JSON文档
    QJsonObject rootObj;
    
    // 保存用户-资源-权限映射
    QJsonObject permissionsObj;
    
    for (auto userIt = m_userResourcePermissions.begin(); userIt != m_userResourcePermissions.end(); ++userIt) {
        QString userId = userIt.key();
        QJsonObject resourcesObj;
        
        for (auto resourceIt = userIt.value().begin(); resourceIt != userIt.value().end(); ++resourceIt) {
            QString resourceId = resourceIt.key();
            QJsonArray permissionsArray;
            
            for (PermissionType permission : resourceIt.value()) {
                permissionsArray.append(static_cast<int>(permission));
            }
            
            resourcesObj[resourceId] = permissionsArray;
        }
        
        permissionsObj[userId] = resourcesObj;
    }
    
    rootObj["permissions"] = permissionsObj;
    
    // 保存用户-资源-角色映射
    QJsonObject rolesObj;
    
    for (auto userIt = m_userResourceRoles.begin(); userIt != m_userResourceRoles.end(); ++userIt) {
        QString userId = userIt.key();
        QJsonObject resourcesObj;
        
        for (auto resourceIt = userIt.value().begin(); resourceIt != userIt.value().end(); ++resourceIt) {
            QString resourceId = resourceIt.key();
            int roleValue = static_cast<int>(resourceIt.value());
            
            resourcesObj[resourceId] = roleValue;
        }
        
        rolesObj[userId] = resourcesObj;
    }
    
    rootObj["roles"] = rolesObj;
    
    // 保存资源-所有者映射
    QJsonObject ownersObj;
    
    for (auto it = m_resourceOwners.begin(); it != m_resourceOwners.end(); ++it) {
        QString resourceId = it.key();
        QString ownerId = it.value();
        
        ownersObj[resourceId] = ownerId;
    }
    
    rootObj["owners"] = ownersObj;
    
    QJsonDocument doc(rootObj);
    
    // 保存配置文件
    QFile file(m_configFilePath);
    if (!file.open(QIODevice::WriteOnly)) {
        qWarning() << "无法创建权限配置文件:" << m_configFilePath;
        return false;
    }
    
    file.write(doc.toJson());
    file.close();
    
    return true;
}

bool PermissionManager::validateOperation(const QString& operatorId, const QString& resourceId, PermissionType requiredPermission)
{
    // 检查资源是否存在
    if (!m_resourceOwners.contains(resourceId)) {
        return false;
    }
    
    // 检查操作者是否是资源所有者
    if (m_resourceOwners[resourceId] == operatorId) {
        return true;
    }
    
    // 检查操作者是否有所需权限
    return hasPermission(operatorId, resourceId, requiredPermission);
}

} // namespace CollaborativeDesign 